package com.hrm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hrm.mapper.EmployeeMapper;
import com.hrm.mapper.JobMapper;
import com.hrm.pojo.Employee;
import com.hrm.pojo.Job;
import com.hrm.pojo.dto.JobRequestParam;
import com.hrm.service.JobService;
import com.hrm.utils.entity.PageResult;
import com.hrm.utils.entity.Result;
import com.hrm.utils.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class JobServiceImpl implements JobService {
    @Autowired
    private JobMapper jobMapper;


    @Override
    public Result selectJobListLikeName(JobRequestParam jobRequestParam) throws Exception {
        //通过分页工具设置分页页数和条数
        PageHelper.startPage(jobRequestParam.getCurrentPage(),jobRequestParam.getPagesize());
        Job job = new Job();
        job.setName(jobRequestParam.getName());
        job.setRemark(jobRequestParam.getRemark());
        Page<Job> jobPage = jobMapper.selectLikeName(job);
        PageResult<Job> pageResult = new PageResult<Job>(jobPage.getTotal(),jobPage.getResult());
        Result result = new Result(true, StatusCode.SUCCESS,"操作成功",pageResult);
        return result;
    }


    @Override
    public boolean updateJob(Job job) throws Exception {
        if (jobMapper.updateByPrimaryKeySelective(job)>0)
            return true;
        return false;
    }

    @Override
    public boolean addJob(Job job) throws Exception {
        if (jobMapper.insertSelective(job)>0)
            return true;
        return false;
    }

    @Override
    @Transactional
    public boolean deleteById(Integer[] ids) throws Exception {
        try {
            // 删除子表中的相关记录
            jobMapper.deleteJobAndRelatedEmployees(Arrays.asList(ids));
            // 删除父表中的记录
            jobMapper.deleteByPrimaryKeys(Arrays.asList(ids));
            return true;
        } catch (Exception e) {
            // 处理异常，回滚事务
            return false;
        }
    }

    @Override
    public Result selectJobList() throws Exception {
        List<Job> jobs = jobMapper.selectJobList();
        Result result = new Result(true, StatusCode.SUCCESS,"操作成功",jobs);
        return result;
    }

    @Override
    public Result selectJobById(Integer id) throws Exception {
        Job job = jobMapper.selectByPrimaryKey(id);
        Result result = new Result(true, StatusCode.SUCCESS,"操作成功",job);
        return result;
    }

}
